package com.leetcode.题库;

import java.util.Arrays;

/**
 * @author 覃国强
 * @date 2022-02-24 11:28
 */
public class 题库_1706_球会落何处 {

  public static void main(String[] args) {
    Solution solution = new Solution();
    int[][] grid = {{1,1,1,-1,-1},{1,1,1,-1,-1},{-1,-1,-1,1,1},{1,1,1,1,-1},{-1,-1,-1,-1,-1}};
    int[] ball = solution.findBall(grid);
    System.out.println(Arrays.toString(ball));
  }

  static
  class Solution {
    public int[] findBall(int[][] grid) {

      if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
        return new int[0];
      }

      int m = grid.length;
      int n = grid[0].length;
      if (n == 1) {
        return new int[] { -1 };
      }

      Ball[] balls = new Ball[n];
      for (int i = 0; i < balls.length; ++i) {
        balls[i] = new Ball(i, i);
      }

      for (int i = 0; i < m; ++i) {
        for (Ball ball : balls) {
          if (ball.end == -1) {
            continue;
          }
          if (grid[i][ball.end] == 1) {
            if (ball.end == n - 1 || grid[i][ball.end + 1] == -1) {
              ball.end = -1;
            } else {
              ball.end = ball.end + 1;
            }
          } else {
            if (ball.end == 0 || grid[i][ball.end - 1] == 1) {
              ball.end = -1;
            } else {
              ball.end = ball.end - 1;
            }
          }
        }
      }

      int[] answer = new int[balls.length];
      for (Ball ball : balls) {
        answer[ball.start] = ball.end;
      }

      return answer;
    }

    static class Ball {

      int start;
      int end;

      public Ball(int start, int end) {
        this.start = start;
        this.end = end;
      }

    }
  }

}
